#!/bin/bash

set -e

ORIGINAL_ICON="$1"  # 原始 1024x1024 图标路径
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

if [ -z "$ORIGINAL_ICON" ]; then
    echo "❌ 错误：请提供原始图标路径"
    echo "使用方法： ./scripts/generate-app-icons.sh path/to/icon-1024.png"
    exit 1
fi

if [ ! -f "$ORIGINAL_ICON" ]; then
    echo "❌ 错误：图标文件不存在：$ORIGINAL_ICON"
    exit 1
fi

# 检查 ImageMagick 是否安装
if ! command -v convert &> /dev/null; then
    echo "❌ 错误：未找到 ImageMagick"
    echo "请先安装：brew install imagemagick"
    exit 1
fi

echo "🎨 开始生成应用图标..."
echo ""

# Android 图标
echo "🤖 生成 Android 图标..."
ANDROID_RES="$PROJECT_ROOT/android/app/src/main/res"

declare -A ANDROID_SIZES=(
    ["mdpi"]=48
    ["hdpi"]=72
    ["xhdpi"]=96
    ["xxhdpi"]=144
    ["xxxhdpi"]=192
)

for density in "${!ANDROID_SIZES[@]}"; do
    size=${ANDROID_SIZES[$density]}
    output_dir="$ANDROID_RES/mipmap-$density"
    mkdir -p "$output_dir"
    convert "$ORIGINAL_ICON" -resize ${size}x${size} "$output_dir/ic_launcher.png"
    echo "  ✅ mipmap-$density: ${size}x${size}"
done

echo ""
echo "🍎 生成 iOS 图标..."

iOS_ICONSET="$PROJECT_ROOT/ios/BellaTravel/Images.xcassets/AppIcon.appiconset"
mkdir -p "$iOS_ICONSET"

# iOS 图标尺寸
declare -a iOS_SIZES=(
    "20:1" "20:2" "20:3"
    "29:1" "29:2" "29:3"
    "40:1" "40:2" "40:3"
    "60:2" "60:3"
    "76:1" "76:2"
    "83.5:2"
    "1024:1"
)

for size_info in "${iOS_SIZES[@]}"; do
    IFS=':' read -r base scale <<< "$size_info"
    actual_size=$(echo "$base * $scale" | bc)
    filename="icon-${base}@${scale}x.png"
    convert "$ORIGINAL_ICON" -resize ${actual_size}x${actual_size} "$iOS_ICONSET/$filename"
    echo "  ✅ $filename: ${actual_size}x${actual_size}"
done

echo ""
echo "✨ 图标生成完成！"
echo "📝 请检查以下目录："
echo "   Android: $ANDROID_RES/mipmap-*/ic_launcher.png"
echo "   iOS: $iOS_ICONSET/"
echo ""
echo "🔄 下一步："
echo "   1. 清理缓存： yarn clean:cache"
echo "   2. 重新运行： yarn android 或 yarn ios"
echo "   3. 检查图标是否正常显示"
